package com.onetime.mall.trading.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.onetime.mall.trading.dao.AddressDao;
import com.onetime.mall.trading.entity.AddressEntity;
import com.onetime.mall.trading.service.AddressService;
import com.onetime.mall.trading.utils.PageUtils;
import com.onetime.mall.trading.utils.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service("addressService")
public class AddressServiceImpl extends ServiceImpl<AddressDao, AddressEntity> implements AddressService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AddressEntity> page = this.page(
                new Query<AddressEntity>().getPage(params),
                new QueryWrapper<AddressEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * // TODO: 2022/3/30  新增地址，默认地址的处理逻辑待优化
     *
     * @param addressEntity 新地址
     * @return true or false
     */
    @Override
    public boolean addAddress(AddressEntity addressEntity) {
        Long userId = addressEntity.getUserId();
        QueryWrapper<AddressEntity> wrapper = new QueryWrapper<>();
        /*新地址为默认地址*/
        if (addressEntity.isDefaultFlag()) {
            wrapper.eq("user_id", userId).eq("default_flag", 1);
            AddressEntity one = baseMapper.selectOne(wrapper);

            /*已有默认，修改状态*/
            if (one != null) {
                one.setDefaultFlag(false);
                baseMapper.updateById(one);
            }
            /*新地址不是默认，*/
        } else {
            /*没有默认地址，则将当前地址设为默认地址*/
            wrapper.eq("user_id", userId).eq("default_flag", 1);
            Long count = baseMapper.selectCount(wrapper);
            if (count == 0) {
                addressEntity.setDefaultFlag(true);
            }
        }
        /*插入新地址*/
        return baseMapper.insert(addressEntity) == 1;
    }

    /**
     * 删除地址，同时要验证用户身份
     *
     * @param addressEntity 要删除的地址
     * @return true or false
     */
    @Override
    public boolean deleteAddress(AddressEntity addressEntity) {
        QueryWrapper<AddressEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", addressEntity.getUserId()).eq("id", addressEntity.getId());
        int delete = baseMapper.delete(wrapper);
        return delete == 1;
    }

    /**
     * 查询一个用户的所有地址信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<AddressEntity> getAddressByUser(Long userId) {
        QueryWrapper<AddressEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return baseMapper.selectList(wrapper);
    }

    /**
     * 通过地址id查询地址的信息，同时验证用户身份
     *
     * @param id
     * @param userId
     * @return
     */
    @Override
    public AddressEntity getAddressById(Long id, Long userId) {
        AddressEntity address = baseMapper.selectById(id);
        if (userId.equals(address.getUserId())) {
            return address;
        }
        return null;
    }

    /**
     * 更新地址信息，同时要验证用户身份（未验证）
     *
     * @param addressEntity
     * @return
     */
    @Override
    public boolean updateAddress(AddressEntity addressEntity) {
        Long userId = addressEntity.getUserId();
        QueryWrapper<AddressEntity> wrapper = new QueryWrapper<>();
        if (addressEntity.isDefaultFlag()) {
            wrapper.eq("user_id", userId).eq("default_flag",1);
            AddressEntity address = baseMapper.selectOne(wrapper);
            /*存在默认地址，就修改成普通*/
            if (address != null) {
                address.setDefaultFlag(false);
                baseMapper.updateById(address);
            }
        } else {
            wrapper.eq("user_id", userId);
            List<AddressEntity> addressEntities = baseMapper.selectList(wrapper);
            AddressEntity address = addressEntities.get(0);
            /*将第一个地址设为默认*/
            address.setDefaultFlag(true);
            baseMapper.updateById(address);
        }
        int update = baseMapper.updateById(addressEntity);
        return update == 1;
    }

}